package com.liuning.graduationdemo.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuning.graduationdemo.common.Constants;
import com.liuning.graduationdemo.common.Result;
import com.liuning.graduationdemo.dto.UserDTO;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

import com.liuning.graduationdemo.service.IUserService;
import com.liuning.graduationdemo.entity.User;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author pumpkin
 * @since 2022-04-07
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private Integer bookNum = 10;

    @Resource
    private IUserService userService;

    /**
     * 导出
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        List<User> list = userService.list();
        //导出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/xx.xlsx");
        //在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
//        writer.addHeaderAlias("username","用户名");
//        writer.addHeaderAlias("password","密码");
//        writer.addHeaderAlias("nickname","昵称");
//        writer.addHeaderAlias("email","邮箱");
//        writer.addHeaderAlias("phone","手机号");
//        writer.addHeaderAlias("address","地址");
//        writer.addHeaderAlias("createTime","创建时间");
//        writer.addHeaderAlias("avatar","头像");

        //一次性写出list中的对象到excel，使用默认样式，强制输出标题
        writer.write(list,true);

        //设置浏览器响应的格式 application/vnd.ms-excel;charset=utf-8
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息","UTF-8");
        response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    @PostMapping("/import")
    public Result importFile(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<User> list = reader.readAll(User.class);
        list.forEach(user -> {
            user.setPassword("888888");
        });
        System.out.println(list);
        return Result.success(userService.saveBatch(list));
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400,"参数错误");
        }

        UserDTO dto = userService.login(userDTO);
        return Result.success(dto);
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400,"参数错误");
        }

        User user = userService.register(userDTO);
        return Result.success(user);
    }

    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        if (user.getId() == null) {
            //创建新用户默认密码 888888
            user.setPassword("888888");
        }
        return Result.success(userService.saveOrUpdate(user));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(userService.removeById(id));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(userService.list());
    }

    /**
     * 用于每日更新医生的挂号数量
     */
    @Scheduled(cron = "0 1 0 * * ?")
    public void updateBookNum() {
        //先查出所有的医生
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role","ROLE_DOCTOR");
        List<User> doctorList = userService.list(queryWrapper);
        for(User doctor : doctorList) {
            doctor.setBookingNumber(bookNum);
            userService.saveOrUpdate(doctor);
        }
    }

    /**
     * 在添加课程时，选择授课老师
     * 查找角色是老师的用户数据
     * @param role
     * @return
     */
    @GetMapping("/role/{role}")
    public Result findUsersByRole(@PathVariable(name = "role") String role) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role",role);
        return Result.success(userService.list(queryWrapper));
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
    }

    @GetMapping("/username/{username}")
    public Result findOne(@PathVariable(name = "username") String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userService.getOne(queryWrapper);
        return Result.success(user);
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(defaultValue = "") String username,
                               @RequestParam(defaultValue = "") String nickname,
                               @RequestParam(defaultValue = "") String address,
                               @RequestParam(defaultValue = "") String roleType) {
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like(Strings.isNotEmpty(username),"username",username);
//        queryWrapper.like(Strings.isNotEmpty(email),"email",email);
//        queryWrapper.like(Strings.isNotEmpty(address),"address",address);
//        queryWrapper.orderByDesc("id");
//        User currentUser = TokenUtils.getCurrentUser();
//        if (currentUser != null) {
//            System.out.println("currentUser:" + currentUser);
//        }
        return Result.success(userService.findPage(new Page<>(pageNum, pageSize),username,nickname,address,roleType));
    }

    //批量删除
    @PostMapping("/del/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        return Result.success(userService.removeBatchByIds(ids));
    }


}

